package com.example.chat.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.domain.AlipayTradeAppPayModel;
import com.alipay.api.request.AlipayTradeAppPayRequest;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.api.response.AlipayTradeAppPayResponse;
import com.alipay.api.response.AlipayTradePagePayResponse;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.chat.beans.*;
import com.example.chat.mapper.*;
import com.example.chat.result.*;
import com.example.chat.utils.*;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.*;

@Service
public class ChatService extends ServiceImpl<MateMapper, Mate> {
    @Resource
    CheckUtils checkUtils;
    @Resource
    Global global;
    @Resource
    VideoMapper videoMapper;
    @Resource
    AdminMapper adminMapper;
    @Resource
    AdminService adminService;
    @Resource
    OrderMapper orderMapper;
    @Resource
    RecordMapper recordMapper;
    @Resource
    PointRecordService pointRecordService;

    public ApiResult<Integer> mateChat(Integer userId, String token, Integer type) {
        ApiResult<Base> apiResult = checkUtils.checkToken(Arrays.asList(userId, token), userId, token, "");
        if (apiResult.getStatus() != 1)
            return new ApiResult<>(apiResult.getStatus(), apiResult.getMsg(), null);
        ApiResult<Integer> result = new ApiResult<>();
        int status = 0;
        String msg = "创建匹配失败";
        try {
            List<Mate> mates = baseMapper.selectByUserId(String.valueOf(userId));
            for (Mate mate : mates) {
                mate.setStatus(3);
                baseMapper.updateById(mate);
            }

            Mate mate = baseMapper.selectByUnMate(System.currentTimeMillis(), type, String.valueOf(userId));
            if (mate == null) {
                mate = new Mate();
                mate.setAdminId(String.valueOf(userId));
                mate.setCreateTime(System.currentTimeMillis());
                mate.setExpireTime(System.currentTimeMillis() + 120000);
                mate.setChannel(UUID.randomUUID().toString());
                mate.setType(type);
                baseMapper.insert(mate);
            } else {
                mate.setUserId(String.valueOf(userId));
                mate.setStatus(2);
                baseMapper.updateById(mate);
            }
            result.setData(mate.getId());
            status = 1;
            msg = "创建匹配成功";
        } catch (Exception e) {
            e.printStackTrace();
        }
        result.setStatus(status);
        result.setMsg(msg);
        return result;
    }

    public ApiResult<Integer> mateChatUnLogin(String uuid, Integer type, HttpServletRequest request) {
        ApiResult<Base> apiResult = checkUtils.checkEmpty(Arrays.asList(uuid, type));
        if (apiResult.getStatus() != 1)
            return new ApiResult<>(apiResult.getStatus(), apiResult.getMsg(), null);
        ApiResult<Integer> result = new ApiResult<>();
        int status = 0;
        String msg = "创建匹配失败";
        try {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("id", uuid);
            jsonObject.put("ip", IpUtil.getIpAddr(request));
            JSONArray jsonArray = new JSONArray();
            jsonArray.add(jsonObject);

            List<Mate> mates = baseMapper.selectByUuid(jsonObject.toString(), jsonArray.toString());
            for (Mate mate : mates) {
                mate.setStatus(3);
                baseMapper.updateById(mate);
            }

            Mate mate = baseMapper.selectByUnMate(System.currentTimeMillis(), type, jsonObject.toString());
            if (mate == null) {
                mate = new Mate();
                mate.setUnLoginAdminId(jsonObject.toString());
                mate.setCreateTime(System.currentTimeMillis());
                mate.setExpireTime(System.currentTimeMillis() + 120000);
                mate.setChannel(UUID.randomUUID().toString());
                mate.setType(type);
                baseMapper.insert(mate);
            } else {
                jsonArray = new JSONArray();
                jsonArray.add(jsonObject);
                mate.setUnLoginUserId(jsonArray.toString());
                mate.setStatus(2);
                baseMapper.updateById(mate);
            }
            result.setData(mate.getId());
            status = 1;
            msg = "创建匹配成功";
        } catch (Exception e) {
            e.printStackTrace();
        }
        result.setStatus(status);
        result.setMsg(msg);
        return result;
    }

    public ApiResult<MateResult> getChatInfo(Integer userId, String uuid, Integer ids, HttpServletRequest request) {
        ApiResult<MateResult> result = new ApiResult<>();
        int status = 0;
        String msg = "匹配失败";
        try {
//            if (uuid.equals(""))
//                global.getExpireTime().put(String.valueOf(userId), System.currentTimeMillis() + 60000);
//            else
//                global.getExpireTime().put(uuid, System.currentTimeMillis() + 60000);

            Mate mate = baseMapper.selectById(ids);
            Map<String, Long> time = global.getExpireTime();
            int count = 0;
            for (String key : time.keySet()) {
                long expireTime = time.get(key);
                if (expireTime >= System.currentTimeMillis()) {
                    count++;
                }
            }

            JSONObject jsonObject = new JSONObject();
            jsonObject.put("id", uuid);
            jsonObject.put("ip", IpUtil.getIpAddr(request));
            JSONArray jsonArray = new JSONArray();
            jsonArray.add(jsonObject);

            MateResult mateResult = new MateResult();
            mateResult.setIp(IpUtil.getIpAddr(request));
            if (userId != null && userId > 0) {
                Admin admin = adminMapper.selectById(userId);
                if (admin != null) {
                    mateResult.setUserPoint(admin.getPoint());
                }
                mateResult.setPointMultiple(global.getConfig().getPointMultiple());
                mateResult.setUnLoginChatTime(global.getConfig().getUnLoginChatTime());
            }
            mateResult.setMateNowId(uuid.equals("") ? baseMapper.selectByUserIdNow(String.valueOf(userId)) : baseMapper.selectByUuidNow(jsonObject.toString(), jsonArray.toString()));

            if (mate != null) {
                if (mate.getExpireTime() >= System.currentTimeMillis()) {
                    mateResult.setId(mate.getId());
                    mateResult.setExpireTime(Global.longToString(mate.getExpireTime()));
                    mateResult.setCreateTime(Global.longToString(mate.getCreateTime()));
                    mateResult.setUserId(mate.getUserId());
                    mateResult.setAdminId(mate.getAdminId());
                    mateResult.setUnLoginAdminId(mate.getUnLoginAdminId());
                    mateResult.setUnLoginUserId(mate.getUnLoginUserId());
                    mateResult.setChannel(mate.getChannel());
                    mateResult.setType(mate.getType());
                    mateResult.setStatus(mate.getStatus());

                    mateResult.setCount(count);
                    result.setData(mateResult);
                    status = 1;
                    msg = "匹配成功";
                } else {
                    status = 2;
                    msg = "匹配已过期";
                    mate.setStatus(4);
                    baseMapper.updateById(mate);
                    mateResult.setCount(count);
                    result.setData(mateResult);
                }
            } else {
                status = 1;
                msg = "未找到该匹配";
                mateResult.setCount(count);
                result.setData(mateResult);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        result.setStatus(status);
        result.setMsg(msg);
        return result;
    }

    public ApiResult<RecordResult> record(Integer userId, String token, String channel, String ids) {
        ApiResult<Base> apiResult = checkUtils.checkToken(Arrays.asList(userId, token, channel, ids), userId, token, "");
        if (apiResult.getStatus() != 1)
            return new ApiResult<>(apiResult.getStatus(), apiResult.getMsg(), null);
        ApiResult<RecordResult> result = new ApiResult<>();
        int status = 0;
        String msg = "开始录制失败";
        try {
            Admin admin = adminMapper.selectById(userId);
            if (admin.getRecordTime() > System.currentTimeMillis() || admin.getTimes() > 0) {
                int times = recordMapper.selectTimesByAdminId(Global.getTodayStartEndTime(1),
                        Global.getTodayStartEndTime(2), userId);
                if (admin.getOrderType() == 1 && times >= global.getConfig().getMonthRecordTimes()) {
                    msg = "包月当日录制次数已用完";
                    result.setStatus(status);
                    result.setMsg(msg);
                    return result;
                }
                if (admin.getOrderType() == 2 && times >= global.getConfig().getYearRecordTimes()) {
                    msg = "包年当日录制次数已用完";
                    result.setStatus(status);
                    result.setMsg(msg);
                    return result;
                }
                String uid = Global.getRandom();
                JSONObject clientRequest = new JSONObject();
                clientRequest.put("region", "CN");
                clientRequest.put("resourceExpiredHour", 24);
                System.out.println("acquire");

                String acquireUrl = "https://api.agora.io/v1/apps/" + global.getConfig().getShengwangAppId() + "/cloud_recording/acquire";
                System.out.println("acquireUrl:" + acquireUrl);
                ApiResult<String> data = OkHttpUtils.builder().url(acquireUrl)
                        .addHeader("Authorization", Base64Encoding.authCode())
                        .addHeader("Content-Type", "application/json")
                        .addParam("cname", channel)
                        .addParam("uid", uid)
                        .addParam("clientRequest", clientRequest)
                        .post(true)
                        .sync();

                Record record = new Record();
                record.setIds(ids);
                record.setCreateAdmin(userId);
                record.setCreateTime(System.currentTimeMillis());
                record.setStatus(1);
                record.setType(1);
                recordMapper.insert(record);

                if (data != null) {
                    if (data.getStatus() == 200) {
                        System.out.println("acquireData:" + data);
                        JSONObject jsonObject = JSON.parseObject(data.getData());

                        String resourceId = jsonObject.getString("resourceId");
                        clientRequest = new JSONObject();
//                    clientRequest.put("token", "");
                        JSONObject recordingConfig = new JSONObject();
                        recordingConfig.put("maxIdleTime", 30);//Number 类型，最长空闲频道时间，单位为秒。默认值为 30。该值需大于等于 5，且小于等于 2,592,000，即 30 天。如果频道内无用户的状态持续超过该时间，录制程序会自动退出。退出后，再次调用
                        recordingConfig.put("channelType", 0);//Number 类型，频道场景

                        JSONObject transcodingConfig = new JSONObject();
                        transcodingConfig.put("height", 360);//高度
                        transcodingConfig.put("width", 640);//宽度
                        transcodingConfig.put("bitrate", 500);//码率
                        transcodingConfig.put("fps", 15);//帧率
                        transcodingConfig.put("mixedVideoLayout", 1);//格式
                        transcodingConfig.put("backgroundColor", "#000000");//背景颜色
                        recordingConfig.put("transcodingConfig", transcodingConfig);

                        JSONObject recordingFileConfig = new JSONObject();
                        JSONArray avFileType = new JSONArray();
                        avFileType.add("hls");
                        avFileType.add("mp4");
                        recordingFileConfig.put("avFileType", avFileType);
                        clientRequest.put("recordingFileConfig", recordingFileConfig);

//                        JSONArray layoutConfig = new JSONArray();
//                        JSONObject layoutConfigObject = new JSONObject();
//                        layoutConfigObject.put("x_axis", 0.1);
//                        layoutConfigObject.put("y_axis", 0.1);
//                        layoutConfigObject.put("width", 0.1);
//                        layoutConfigObject.put("height", 0.1);
//                        layoutConfigObject.put("alpha", 1);
//                        layoutConfigObject.put("render_mode", 1);
//                        layoutConfig.add(layoutConfigObject);
//                        clientRequest.put("layoutConfig", layoutConfig);

                        JSONObject storageConfig = new JSONObject();
                        storageConfig.put("accessKey", global.getConfig().getAliyunId());
                        storageConfig.put("region", 0);
                        storageConfig.put("vendor", 2);
                        storageConfig.put("bucket", "goodbon");
                        storageConfig.put("secretKey", global.getConfig().getAliyunKey());
                        JSONArray fileNamePrefix = new JSONArray();
                        fileNamePrefix.add(String.valueOf(userId));
                        fileNamePrefix.add(ids);
                        storageConfig.put("fileNamePrefix", fileNamePrefix);
                        clientRequest.put("storageConfig", storageConfig);
                        clientRequest.put("recordingConfig", recordingConfig);

                        System.out.println("start");
                        String url = "https://api.agora.io/v1/apps/" + global.getConfig().getShengwangAppId() + "/cloud_recording" + "/resourceid/" + resourceId + "/mode/mix/start";
                        System.out.println("startUrl:" + url);
                        data = OkHttpUtils.builder().url(url)
                                .addHeader("Authorization", Base64Encoding.authCode())
                                .addHeader("Content-Type", "application/json")
                                .addParam("cname", channel)
                                .addParam("uid", uid)
                                .addParam("clientRequest", clientRequest)
                                .post(true)
                                .sync();
                        if (data.getStatus() == 200) {
                            System.out.println("startReturnData:" + data.getData());
                            JSONObject resultJson = JSON.parseObject(data.getData());
                            RecordResult recordResult = new RecordResult();
                            recordResult.setResourceId(resultJson.getString("resourceId"));
                            recordResult.setSid(resultJson.getString("sid"));
                            recordResult.setUid(uid);
                            result.setData(recordResult);
                            status = 1;
                            msg = "开始录制成功";

                            if (record.getId() != null) {
                                record.setResourceId(resultJson.getString("resourceId"));
                                record.setSid(resultJson.getString("sid"));
                                record.setStatus(2);
                                record.setUid(uid);
                                record.setChannel(channel);
                                recordMapper.updateById(record);
                            }
                            if (admin.getRecordTime() <= System.currentTimeMillis()) {
                                admin.setTimes(admin.getTimes() - 1);
                                adminMapper.updateById(admin);
                            }
                            // TODO 开始计算积分
                            pointRecordService.videoPoint1(ids, record.getId());
                        } else {
                            msg = "开始录制失败";
                            record.setStatus(3);
                            recordMapper.updateById(record);
                        }
                    } else {
                        msg = "获取resourceId失败";
                        record.setStatus(3);
                        recordMapper.updateById(record);
                    }
                } else {
                    msg = "获取resourceId失败";
                    record.setStatus(3);
                    recordMapper.updateById(record);
                }
            } else msg = "录制期限期限已到期或没有次数";
        } catch (Exception e) {
            e.printStackTrace();
        }
        result.setStatus(status);
        result.setMsg(msg);
        return result;
    }


    public ApiResult<RecordResult> emergencyRecord(String uuid, String channel, String ids) {
        ApiResult<RecordResult> result = new ApiResult<>();
        int status = 0;
        String msg = "开始录制失败";
        try {
            String uid = Global.getRandom();
            JSONObject clientRequest = new JSONObject();
            clientRequest.put("region", "CN");
            clientRequest.put("resourceExpiredHour", 24);
            System.out.println("acquire");

            String acquireUrl = "https://api.agora.io/v1/apps/" + global.getConfig().getShengwangAppId() + "/cloud_recording/acquire";
            System.out.println("acquireUrl:" + acquireUrl);
            ApiResult<String> data = OkHttpUtils.builder().url(acquireUrl)
                    .addHeader("Authorization", Base64Encoding.authCode())
                    .addHeader("Content-Type", "application/json")
                    .addParam("cname", channel)
                    .addParam("uid", uid)
                    .addParam("clientRequest", clientRequest)
                    .post(true)
                    .sync();

            Record record = new Record();
            record.setIds(ids);
            record.setCreateTime(System.currentTimeMillis());
            record.setStatus(1);
            record.setType(2);
            recordMapper.insert(record);

            if (data != null) {
                if (data.getStatus() == 200) {
                    System.out.println("acquireData:" + data);
                    JSONObject jsonObject = JSON.parseObject(data.getData());

                    String resourceId = jsonObject.getString("resourceId");
                    clientRequest = new JSONObject();
//                    clientRequest.put("token", "");
                    JSONObject recordingConfig = new JSONObject();
                    recordingConfig.put("maxIdleTime", 30);//Number 类型，最长空闲频道时间，单位为秒。默认值为 30。该值需大于等于 5，且小于等于 2,592,000，即 30 天。如果频道内无用户的状态持续超过该时间，录制程序会自动退出。退出后，再次调用
                    recordingConfig.put("channelType", 0);//Number 类型，频道场景

                    JSONObject transcodingConfig = new JSONObject();
                    transcodingConfig.put("height", 360);//高度
                    transcodingConfig.put("width", 640);//宽度
                    transcodingConfig.put("bitrate", 500);//码率
                    transcodingConfig.put("fps", 15);//帧率
                    transcodingConfig.put("mixedVideoLayout", 3);//格式
                    transcodingConfig.put("backgroundColor", "#000000");//背景颜色
                    recordingConfig.put("transcodingConfig", transcodingConfig);

                    JSONArray layoutConfig = new JSONArray();
                    JSONObject layoutConfigObject = new JSONObject();
                    layoutConfigObject.put("x_axis", 0);
                    layoutConfigObject.put("y_axis", 0);
                    layoutConfigObject.put("width", 1);
                    layoutConfigObject.put("height", 1);
                    layoutConfigObject.put("alpha", 1);
                    layoutConfigObject.put("render_mode", 1);
                    layoutConfig.add(layoutConfigObject);
                    transcodingConfig.put("layoutConfig", layoutConfig);

                    JSONObject recordingFileConfig = new JSONObject();
                    JSONArray avFileType = new JSONArray();
                    avFileType.add("hls");
                    avFileType.add("mp4");
                    recordingFileConfig.put("avFileType", avFileType);
                    clientRequest.put("recordingFileConfig", recordingFileConfig);

                    JSONObject storageConfig = new JSONObject();
                    storageConfig.put("accessKey", global.getConfig().getAliyunId());
                    storageConfig.put("region", 0);
                    storageConfig.put("vendor", 2);
                    storageConfig.put("bucket", "goodbon");
                    storageConfig.put("secretKey", global.getConfig().getAliyunKey());
                    JSONArray fileNamePrefix = new JSONArray();
                    fileNamePrefix.add(uuid);
                    fileNamePrefix.add(ids);
                    storageConfig.put("fileNamePrefix", fileNamePrefix);
                    clientRequest.put("storageConfig", storageConfig);
                    clientRequest.put("recordingConfig", recordingConfig);

                    System.out.println("start");
                    String url = "https://api.agora.io/v1/apps/" + global.getConfig().getShengwangAppId() + "/cloud_recording" + "/resourceid/" + resourceId + "/mode/mix/start";
                    System.out.println("startUrl:" + url);
                    data = OkHttpUtils.builder().url(url)
                            .addHeader("Authorization", Base64Encoding.authCode())
                            .addHeader("Content-Type", "application/json")
                            .addParam("cname", channel)
                            .addParam("uid", uid)
                            .addParam("clientRequest", clientRequest)
                            .post(true)
                            .sync();
                    System.out.println("startReturnData:" + data.getData());
                    if (data.getStatus() == 200) {
                        System.out.println("startReturnData:" + data.getData());
                        JSONObject resultJson = JSON.parseObject(data.getData());
                        RecordResult recordResult = new RecordResult();
                        recordResult.setResourceId(resultJson.getString("resourceId"));
                        recordResult.setSid(resultJson.getString("sid"));
                        recordResult.setUid(uid);
                        result.setData(recordResult);
                        status = 1;
                        msg = "开始录制成功";

                        if (record.getId() != null) {
                            record.setResourceId(resultJson.getString("resourceId"));
                            record.setSid(resultJson.getString("sid"));
                            record.setStatus(2);
                            record.setUid(uid);
                            record.setChannel(channel);
                            recordMapper.updateById(record);
                        }
                    } else {
                        msg = "开始录制失败";
                        record.setStatus(3);
                        recordMapper.updateById(record);
                    }
                } else {
                    msg = "获取resourceId失败";
                    record.setStatus(3);
                    recordMapper.updateById(record);
                }
            } else {
                msg = "获取resourceId失败";
                record.setStatus(3);
                recordMapper.updateById(record);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        result.setStatus(status);
        result.setMsg(msg);
        return result;
    }

    public ApiResult<RecordStatusResult> recordStatus(Integer userId, String token, String resourceId, String sid, int type) {
        if (type == 1) {
            ApiResult<Base> apiResult = checkUtils.checkToken(Arrays.asList(userId, token, resourceId, sid), userId, token, "");
            if (apiResult.getStatus() != 1)
                return new ApiResult<>(apiResult.getStatus(), apiResult.getMsg(), null);
        }
        ApiResult<RecordStatusResult> result = new ApiResult<>();
        int status = 0;
        String msg = "获取录制状态失败";
        try {
            String url = "https://api.agora.io/v1/apps/" + global.getConfig().getShengwangAppId() + "/cloud_recording/resourceid/" + resourceId + "/sid/" + sid + "/mode/mix/query";
            System.out.println("url:" + url);
            ApiResult<String> data = OkHttpUtils.builder().url(url)
                    .addHeader("Authorization", Base64Encoding.authCode())
                    .addHeader("Content-Type", "application/json")
                    .get()
                    .sync();
            if (data != null) {
                int code = data.getStatus();
                if (code == 200) {
                    System.out.println(data.getData());
                    RecordStatusResult recordStatusResult = JSON.parseObject(data.getData(), RecordStatusResult.class);
                    if (recordStatusResult != null) {
                        result.setData(recordStatusResult);
                        status = 1;
                        msg = "获取录制状态成功";
                    } else msg = "无法获取录制状态";
                } else {
                    if (code == 404) {
                        Record record = recordMapper.selectByResourceIdAndSid(resourceId, sid);
                        if (record != null) {
                            record.setStatus(3);
                            recordMapper.updateById(record);
                        }
                        status = 1;
                        msg = "录制已停止";
                    }
                }
            } else {
                Record record = recordMapper.selectByResourceIdAndSid(resourceId, sid);
                if (record != null) {
                    record.setStatus(3);
                    recordMapper.updateById(record);
                }
                msg = "无法获取录制状态";
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        result.setStatus(status);
        result.setMsg(msg);
        return result;
    }

    public ApiResult<RecordStopResult> recordStop(Integer userId, String token, String resourceId, String sid, String uid, String channel, Integer ids, int type) {
        if (type == 1) {
            ApiResult<Base> apiResult = checkUtils.checkToken(Arrays.asList(userId, token, channel, resourceId, sid, uid), userId, token, "");
            if (apiResult.getStatus() != 1)
                return new ApiResult<>(apiResult.getStatus(), apiResult.getMsg(), null);
        }
        ApiResult<RecordStopResult> result = new ApiResult<>();
        int status = 0;
        String msg = "停止录制失败";
        try {
            JSONObject clientRequest = new JSONObject();
            clientRequest.put("async_stop", false);
            ApiResult<String> data = OkHttpUtils.builder().url("https://api.agora.io/v1/apps/" + global.getConfig().getShengwangAppId() + "/cloud_recording/resourceid/" + resourceId + "/sid/" + sid + "/mode/mix/stop")
                    .addHeader("Authorization", Base64Encoding.authCode())
                    .addHeader("Content-Type", "application/json")
                    .addParam("cname", channel)
                    .addParam("uid", uid)
                    .addParam("clientRequest", clientRequest)
                    .post(true)
                    .sync();
            if (data != null) {
                System.out.println("stopData:" + data.getData());
                int code = data.getStatus();
                if (code == 200) {
                    long endTime = System.currentTimeMillis();
                    RecordStopResult recordStopResult = JSON.parseObject(data.getData(), RecordStopResult.class);
                    if (recordStopResult != null) {
                        Record record = recordMapper.selectByResourceIdAndSid(resourceId, sid);
                        if (record != null) {
                            System.out.println(data.getData());
                            List<RecordStopResult.File> fileList = recordStopResult.getServerResponse().fileList;
                            for (RecordStopResult.File file : fileList) {
                                if (file.fileName.endsWith(".mp4")) {
                                    Video video = new Video();
                                    video.setFilePath(file.fileName);
                                    video.setCreateAdmin(userId);
                                    video.setChatAdminId(ids);
                                    video.setCreateTime(System.currentTimeMillis());
                                    video.setType(record.getType());
                                    videoMapper.insert(video);
                                }
                            }
                            result.setData(recordStopResult);
                            status = 1;
                            msg = "停止录制成功";

                            record.setStatus(3);
                            recordMapper.updateById(record);
                        } else msg = "录制不存在";
                    } else msg = "无法停止录制";
                } else {
                    if (code == 404) {
                        msg = "录制已停止";
                        status = 1;
                    }
                }
            } else msg = "停止录制失败";
        } catch (Exception e) {
            e.printStackTrace();
        }
        result.setStatus(status);
        result.setMsg(msg);
        return result;
    }

    @Transactional
    public ApiResult<String> payOrder(Integer userId, String token, Integer type, Integer payType) {
        ApiResult<Base> apiResult = checkUtils.checkToken(Arrays.asList(userId, token, type), userId, token, "");
        if (apiResult.getStatus() != 1)
            return new ApiResult<>(apiResult.getStatus(), apiResult.getMsg(), null);
        ApiResult<String> result = new ApiResult<>();
        int status = 0;
        String msg = "下单失败";
        try {
            String number = userId + global.getTimeSdf().format(new Date(System.currentTimeMillis()));
            Admin admin = adminMapper.selectById(userId);
            if (admin != null) {
                double money = 0;
                String title = "";
                if (type == 1) {
                    money = global.getConfig().getOncePay();
                    title = "视频按次收费";
                }
                if (type == 2) {
                    money = global.getConfig().getMonthPay();
                    title = "视频包月收费";
                }
                if (type == 3) {
                    money = global.getConfig().getYearPay();
                    title = "视频包年收费";
                }

                if (payType == 1) {
                    AlipayClient alipayClient = new DefaultAlipayClient("https://openapi.alipay.com/gateway.do", AlipayConfig.app_id, AlipayConfig.merchant_private_key, "json", "UTF-8", AlipayConfig.alipay_public_key, "RSA2");
                    AlipayTradePagePayRequest request = new AlipayTradePagePayRequest();
//异步接收地址，仅支持http/https，公网可访问
                    request.setNotifyUrl(AlipayConfig.notify_url);
//同步跳转地址，仅支持http/https
                    request.setReturnUrl(AlipayConfig.return_url);
/******必传参数******/
                    JSONObject bizContent = new JSONObject();
//商户订单号，商家自定义，保持唯一性
                    bizContent.put("out_trade_no", number);
//支付金额，最小值0.01元
                    bizContent.put("total_amount", money);
//订单标题，不可使用特殊符号
                    bizContent.put("subject", title);
//电脑网站支付场景固定传值FAST_INSTANT_TRADE_PAY
                    bizContent.put("product_code", "FAST_INSTANT_TRADE_PAY");

                    request.setBizContent(bizContent.toString());
                    AlipayTradePagePayResponse response = alipayClient.pageExecute(request);
                    if (response.isSuccess()) {
                        Order order = new Order();
                        order.setCreateAdmin(userId);
                        order.setCreateTime(System.currentTimeMillis());
                        order.setMoney(money);
                        order.setNumber(number);
                        order.setPhone(admin.getTel());
                        order.setStatus(1);
                        orderMapper.insert(order);

                        System.out.println("下单成功");
                        result.setData(response.getBody());
                        status = 1;
                        msg = "下单成功";
                    } else {
                        System.out.println("下单失败");
                        msg = "下单失败";
                    }
                }
                if (payType == 2) {
                    AlipayClient alipayClient = new DefaultAlipayClient("https://openapi.alipay.com/gateway.do", AlipayConfig.app_app_id, AlipayConfig.app_merchant_private_key, "json", "UTF-8", AlipayConfig.app_alipay_public_key, "RSA2");
                    AlipayTradeAppPayRequest request = new AlipayTradeAppPayRequest();
                    AlipayTradeAppPayModel model = new AlipayTradeAppPayModel();
                    model.setSubject(title);
                    model.setOutTradeNo(number);
                    model.setTimeoutExpress("30m");
                    model.setTotalAmount(String.valueOf(money));
                    model.setProductCode("QUICK_MSECURITY_PAY");
                    request.setBizModel(model);
                    request.setNotifyUrl(AlipayConfig.notify1_url);
                    try {
                        //这里和普通的接口调用不同，使用的是sdkExecute
                        AlipayTradeAppPayResponse response = alipayClient.sdkExecute(request);
                        if (response.isSuccess()) {
                            Order order = new Order();
                            order.setCreateAdmin(userId);
                            order.setCreateTime(System.currentTimeMillis());
                            order.setMoney(money);
                            order.setNumber(number);
                            order.setPhone(admin.getTel());
                            order.setStatus(1);
                            orderMapper.insert(order);

                            System.out.println("下单成功");
                            result.setData(response.getBody());
                            status = 1;
                            msg = "下单成功";
                        } else {
                            msg = "下单失败";
                        }
                    } catch (AlipayApiException e) {
                        e.printStackTrace();
                        msg = "下单失败";
                    }
                }
                if (payType == 3) {
                    int points = (int) (money * 100);
                    if (admin.getPoint() >= points) {

                        Order order = new Order();
                        order.setCreateAdmin(userId);
                        order.setCreateTime(System.currentTimeMillis());
                        order.setMoney(money);
                        order.setNumber(number);
                        order.setPhone(admin.getTel());
                        order.setPoints(points);
                        order.setStatus(2);
                        orderMapper.insert(order);
                        pointRecordService.orderPoint(admin, points, order.getId());
                        adminService.updateBySuccessPay(admin, title);

                        System.out.println("下单成功");
                        result.setData(String.valueOf(admin.getPoint()));
                        status = 1;
                        msg = "下单成功";
                    } else {
                        System.out.println("下单失败");
                        msg = "下单失败";
                    }
                }
            } else msg = "用户不存在";
        } catch (Exception e) {
            e.printStackTrace();
        }
        result.setStatus(status);
        result.setMsg(msg);
        return result;
    }

    public ApiResult<RecordingResult> recordingStatus(String ids) {
        ApiResult<RecordingResult> result = new ApiResult<>();
        int status = 1;
        String msg = "获取失败";
        try {
            RecordingResult recordingResult = recordMapper.selectByIds(ids);
            if (recordingResult != null) {
                result.setData(recordingResult);
                status = 1;
                msg = "获取成功";
            } else msg = "暂无录制记录";
        } catch (Exception e) {
            e.printStackTrace();
        }
        result.setStatus(status);
        result.setMsg(msg);
        return result;
    }

    public ApiResult<Base> endChat(Integer userId, String uuid, Integer ids, HttpServletRequest request) {
        ApiResult<Base> result = new ApiResult<>();
        int status = 0;
        String msg = "结束失败";
        try {
            Mate mate = baseMapper.selectById(ids);
            if (mate != null) {
                if (mate.getUserId().equals(String.valueOf(userId)) ||
                        mate.getAdminId().equals(String.valueOf(userId)) ||
                        mate.getUnLoginAdminId().contains(uuid) ||
                        mate.getUnLoginUserId().contains(uuid)) {
                    mate.setStatus(3);
                    baseMapper.updateById(mate);
                    status = 1;
                    msg = "结束聊天成功";
                } else msg = "非聊天用户无法结束聊天";
            } else msg = "匹配不存在";
        } catch (Exception e) {
            e.printStackTrace();
        }
        result.setStatus(status);
        result.setMsg(msg);
        return result;
    }

    public ApiResult<Integer> updateOnline(Integer userId, String uuid, HttpServletRequest request) {
        ApiResult<Integer> result = new ApiResult<>();
        int status = 0;
        String msg = "更新在线状态失败";
        try {
            if (uuid.equals(""))
                global.add(String.valueOf(userId), System.currentTimeMillis() + 60000);
            else
                global.add(uuid, System.currentTimeMillis() + 60000);

            Map<String, Long> time = global.getExpireTime();
            int count = 0;
            for (String key : time.keySet()) {
                long expireTime = time.get(key);
                if (expireTime >= System.currentTimeMillis()) {
                    count++;
                }
            }
            result.setData(count);
            status = 1;
            msg = "更新在线状态成功";
        } catch (Exception e) {
            e.printStackTrace();
        }
        result.setStatus(status);
        result.setMsg(msg);
        return result;
    }

    public ApiResult<OnlineResult> updateOnlineNew(Integer userId, String uuid) {
        ApiResult<OnlineResult> result = new ApiResult<>();
        OnlineResult onlineResult = new OnlineResult();
        int status = 0;
        String msg = "更新在线状态失败";
        try {
            if (uuid.equals("")) {
                global.add(String.valueOf(userId), System.currentTimeMillis() + 60000);
            } else {
                global.add(uuid, System.currentTimeMillis() + 60000);
            }

            Map<String, Long> time = global.getExpireTime();
            int count = 0;
            for (String key : time.keySet()) {
                long expireTime = time.get(key);
                if (expireTime >= System.currentTimeMillis()) {
                    count++;
                }
            }
            onlineResult.setOnlineCount(count);
            if (userId != null) {
                Admin admin = adminMapper.selectById(userId);
                if (admin != null) {
                    onlineResult.setUserPoint(admin.getPoint());
                    onlineResult.setPointMultiple(global.getConfig().getPointMultiple());
                    onlineResult.setUnLoginChatTime(global.getConfig().getUnLoginChatTime());
                }
            }

            status = 1;
            msg = "更新在线状态成功";
        } catch (Exception e) {
            e.printStackTrace();
        }
        result.setData(onlineResult);
        result.setStatus(status);
        result.setMsg(msg);
        return result;
    }
}
